package com.ethink.platform.controller.order;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSONObject;
import com.ethink.framework.common.web.BaseController;
import com.ethink.framework.common.web.context.SPRequestContextHolder;
import com.ethink.framework.common.web.response.CommonResponse;
import com.ethink.mdm.api.MateFacade;
import com.ethink.mdm.api.info.MateSkuInfo;
import com.ethink.order.api.TobSaleOrderFacade;
import com.ethink.order.api.TobSaleReturnOrderFacade;
import com.ethink.order.api.enums.TobSaleReturnOrderReturnStatusEnum;
import com.ethink.order.api.info.TobSaleDetailOrderInfo;
import com.ethink.order.api.info.TobSaleOrderInfo;
import com.ethink.order.api.info.TobSaleReturnDetailOrderInfo;
import com.ethink.order.api.info.TobSaleReturnOrderInfo;
import com.ethink.order.api.model.TobSaleReturnDetailModel;
import com.ethink.order.api.model.TobSaleReturnModeModel;
import com.ethink.order.api.model.TobSaleReturnModel;
import com.ethink.order.api.model.TransferTobSaleReturnModel;
import com.ethink.order.api.request.TobSaleReturnOrderAddRequest;
import com.ethink.order.api.request.TobSaleReturnOrderQueryRequest;
import com.ethink.order.api.request.TobSaleReturnOrderTakePlaceInsertQueryRequest;
import com.ethink.order.api.request.TobSaleReturnOrderUpdateRequest;
import com.ethink.order.api.response.TobSaleOrderDetailResponse;
import com.ethink.order.api.response.TobSaleReturnQueryDetailResponse;
import com.ethink.order.api.response.TobSaleTransferOrderQueryResponse;
import com.ethink.order.api.utils.EthinkStrUtil;
import com.ethink.platform.common.properties.PlatformCommonProperties;
import com.ethink.platform.controller.order.info.ExportInfo;
import com.ethink.platform.manager.ExportManager;
import com.ethink.platform.manager.SaleReturnManager;
import com.ethink.system.api.SystemTodoFacade;
import com.ethink.system.api.enums.SystemTodoTodoTypeEnum;
import com.ethink.system.api.request.SystemTodoAddRequest;
import com.ethink.warehouse.api.LogisticsTraceApplyOrderFacade;
import com.ethink.warehouse.api.SubWarehouseFacade;
import com.ethink.warehouse.api.enums.SubjectEnum;
import com.ethink.warehouse.api.info.SubWarehouseInfo;
import com.ethink.warehouse.api.request.LogisticsTraceApplyDeleteRequest;
import com.google.common.collect.Lists;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 预售退单 Controller
 *
 * @author default
 * @date 2022-12-08
 */
@Tag(name = "TobSaleReturnOrderController", description = "预售退单 Controller")
@RestController
@Slf4j
@RequestMapping("platform-server/v1/system-service")
public class TobSaleReturnOrderController extends BaseController {

    @Autowired
    private TobSaleReturnOrderFacade tobSaleReturnOrderFacade;


    @Autowired
    private TobSaleOrderFacade tobSaleOrderFacade;


    @Autowired
    private SubWarehouseFacade subWarehouseFacade;

    @Autowired
    private MateFacade mateFacade;

    @Autowired
    private SaleReturnManager saleReturnManager;

    @Autowired
    private PlatformCommonProperties commonProperties;

    @Autowired
    private SystemTodoFacade systemTodoFacade;

    @Autowired
    private LogisticsTraceApplyOrderFacade logisticsTraceApplyOrderFacade;

    @Autowired
    private ExportManager exportManager;

    @Operation(summary = "预售转退单查询")
    @GetMapping("/tobSaleReturnOrder/transfer/{id}")
    public CommonResponse<TobSaleTransferOrderQueryResponse> tobSaleTransferReturnOrderQuery(@PathVariable Long id) {
        TobSaleTransferOrderQueryResponse response = new TobSaleTransferOrderQueryResponse();
        TobSaleOrderInfo tobSaleOrderInfo = tobSaleOrderFacade.queryTobSaleOrderById(id);
        response.setMain(tobSaleOrderInfo);
        TobSaleOrderDetailResponse detailResponse = tobSaleOrderFacade.queryDetailTobSaleOrder(id, 1);
        //查询预售退商品信息
        List<TobSaleReturnDetailOrderInfo> returnInfos = tobSaleReturnOrderFacade.queryDetailListByTobSaleOrderNo(tobSaleOrderInfo.getOrderNo());
        Map<String, List<TobSaleReturnDetailOrderInfo>> returnGroup = returnInfos.stream().collect(Collectors.groupingBy(TobSaleReturnDetailOrderInfo::getMateSku));
        //mateSku分组
        Map<String, List<TobSaleDetailOrderInfo>> itemMap = detailResponse.getSaleItem().stream()
                .collect(Collectors.groupingBy(TobSaleDetailOrderInfo::getMateSku));
        List<TransferTobSaleReturnModel> item = new ArrayList<>();
        Integer key = 0;
        for (Map.Entry<String, List<TobSaleDetailOrderInfo>> stringListEntry : itemMap.entrySet()) {
            TransferTobSaleReturnModel returnModel = new TransferTobSaleReturnModel();
            List<TobSaleDetailOrderInfo> value = stringListEntry.getValue();
            //计算数量
            int sum = value.stream().mapToInt(TobSaleDetailOrderInfo::getQty).sum();
            int settleQty = value.stream().mapToInt(TobSaleDetailOrderInfo::getSettleQty).sum();
            List<TobSaleReturnDetailOrderInfo> returnDetailOrderInfos = returnGroup.get(stringListEntry.getKey());
            TobSaleDetailOrderInfo tobSaleDetailOrderInfo = value.get(0);
            returnModel.setKey(key);
            returnModel.setOrderNo(tobSaleDetailOrderInfo.getOrderNo());
            returnModel.setMateSku(tobSaleDetailOrderInfo.getMateSku());
            returnModel.setMateCode(tobSaleDetailOrderInfo.getMateCode());
            returnModel.setMateName(tobSaleDetailOrderInfo.getMateName());
            returnModel.setMateSkuName(tobSaleDetailOrderInfo.getMateSkuName());
            returnModel.setCategoryName(tobSaleDetailOrderInfo.getCategoryName());
            returnModel.setBrandCode(tobSaleDetailOrderInfo.getBrandCode());
            returnModel.setBrandName(tobSaleDetailOrderInfo.getBrandName());
            returnModel.setUnitCode(tobSaleDetailOrderInfo.getUnitCode());
            returnModel.setUnitName(tobSaleDetailOrderInfo.getUnitName());
            returnModel.setProductSpecification(tobSaleDetailOrderInfo.getProductSpecification());
            if (CollUtil.isNotEmpty(returnDetailOrderInfos)) {
                int returnQty = returnDetailOrderInfos.stream().mapToInt(TobSaleReturnDetailOrderInfo::getReturnQty).sum();
                returnModel.setQty(sum - settleQty - returnQty);
            } else {
                returnModel.setQty(sum - settleQty);
            }
            if (returnModel.getQty() > 0) {
                item.add(returnModel);
                key++;
            }
        }
        response.setItem(item);
        return succeedWith(response);
    }

    @Operation(summary = "新增")
    @PostMapping("/tobSaleReturnOrder/add")
    public CommonResponse addTobSaleReturnOrder(@Validated @RequestBody TobSaleReturnOrderAddRequest request) {
        request.setCreateUserCode(SPRequestContextHolder.getCurrentSystemUserLoginName());
        request.setCreateUserName(SPRequestContextHolder.getCurrentSystemUserRealName());
        SubWarehouseInfo subWarehouseInfo = subWarehouseFacade.getSubWarehouseByCode(request.getSubWarehouseCode());
        request.setSubWarehouseName(subWarehouseInfo.getSubWarehouseName());
        tobSaleReturnOrderFacade.add(request);
        return succeed();
    }

    @Operation(summary = "分页查询")
    @GetMapping("/tobSaleReturnOrder/pageQuery")
    public CommonResponse<List<TobSaleReturnModel>> queryTobSaleReturnOrder(TobSaleReturnOrderQueryRequest request) {
        return succeedWithPage(tobSaleReturnOrderFacade.pageQuery(request));
    }

    @Operation(summary = "导出")
    @GetMapping("/tobSaleReturnOrder/export")
    public CommonResponse<ExportInfo> exportTobSaleReturnOrder(TobSaleReturnOrderQueryRequest request) {
        return succeedWith(exportManager.exportTobSaleReturnOrder(request));
    }

    @Operation(summary = "货品模式分页查询")
    @GetMapping("/tobSaleReturnOrder/pageModeQuery")
    public CommonResponse<List<TobSaleReturnModeModel>> queryTobSaleReturnOrderMode(TobSaleReturnOrderQueryRequest request) {
        return succeedWithPage(tobSaleReturnOrderFacade.pageModeQuery(request));
    }

    @Operation(summary = "货品模式导出")
    @GetMapping("/tobSaleReturnOrder/modeExport")
    public CommonResponse<ExportInfo> exportTobSaleReturnOrderMode(TobSaleReturnOrderQueryRequest request) {
        return succeedWith(exportManager.exportTobSaleReturnOrderMode(request));
    }

    @Operation(summary = "详情")
    @GetMapping("/tobSaleReturnOrder/detail/{id}")
    public CommonResponse<TobSaleReturnQueryDetailResponse> getTobSaleReturnOrderById(@PathVariable Long id) {
        TobSaleReturnQueryDetailResponse response = tobSaleReturnOrderFacade.queryDetail(id);
        TobSaleReturnModel main = response.getMain();
        //查询主仓库信息
        SubWarehouseInfo subWarehouseInfo = subWarehouseFacade.getSubWarehouseByCode(main.getSubWarehouseCode());
        main.setWarehouseCode(subWarehouseInfo.getWarehouseCode());
        main.setWarehouseName(subWarehouseInfo.getWarehouseName());
        List<String> mateSku = CollUtil.getFieldValues(response.getItem(), "mateSku", String.class);
        //填充商品信息
        List<MateSkuInfo> mateSkuInfos = mateFacade.queryMateSkuBySkuCodeList(mateSku);
        Map<String, MateSkuInfo> mateMap = new HashMap<>();
        for (MateSkuInfo mateSkuInfo : mateSkuInfos) {
            mateMap.put(mateSkuInfo.getMateSku(), mateSkuInfo);
        }
        for (TobSaleReturnDetailModel tobSaleReturnDetailModel : response.getItem()) {
            MateSkuInfo mateSkuInfo = mateMap.get(tobSaleReturnDetailModel.getMateSku());
            if (ObjectUtil.isNotEmpty(mateSkuInfo)) {
                tobSaleReturnDetailModel.setBrandCode(mateSkuInfo.getBrandCode());
                tobSaleReturnDetailModel.setBrandName(mateSkuInfo.getBrandName());
                tobSaleReturnDetailModel.setCategoryName(EthinkStrUtil
                        .stitchStrings(mateSkuInfo.getGeneraCodeName(), mateSkuInfo.getMinorDefectsCodeName(), mateSkuInfo.getSubclassCodeName()));
                tobSaleReturnDetailModel.setMateSkuName(mateSkuInfo.getMateSkuName());
                tobSaleReturnDetailModel.setProductSpecification(mateSkuInfo.getProductSpecification());
                tobSaleReturnDetailModel.setUnitCode(mateSkuInfo.getUnitCode());
                tobSaleReturnDetailModel.setUnitName(mateSkuInfo.getUnitName());
            }
        }
        return succeedWith(response);
    }


    @Operation(summary = "编辑-草稿状态")
    @PutMapping("/tobSaleReturnOrder/update")
    public CommonResponse updateTobSaleReturnOrder(@Validated @RequestBody TobSaleReturnOrderUpdateRequest request) {
        if (StringUtils.isNotEmpty(request.getSubWarehouseCode())) {
            SubWarehouseInfo subWarehouseByCode = subWarehouseFacade.getSubWarehouseByCode(request.getSubWarehouseCode());
            request.setSubWarehouseName(subWarehouseByCode.getSubWarehouseName());
        }
        tobSaleReturnOrderFacade.update(request);
        return succeed();
    }


    @Operation(summary = "删除-草稿状态")
    @DeleteMapping("/tobSaleReturnOrder/delete/{id}")
    public CommonResponse deleteTobSaleReturnOrder(@PathVariable("id") Long id) {
        tobSaleReturnOrderFacade.delete(id);
        return succeed();
    }


    @Operation(summary = "审批通过(订单状态 = 2)")
    @PutMapping("/tobSaleReturnOrder/pass/{id}")
    public CommonResponse tobSaleReturnPass(@PathVariable Long id) {
        tobSaleReturnOrderFacade.pass(id);
        TobSaleReturnQueryDetailResponse response = tobSaleReturnOrderFacade.queryDetail(id);
        //创建待入申请
        TobSaleReturnOrderInfo tobSaleReturnOrderInfo = BeanUtil.copyProperties(response.getMain(), TobSaleReturnOrderInfo.class);
        List<TobSaleReturnDetailOrderInfo> item = response.getItem().stream()
                .map(a -> BeanUtil.copyProperties(a, TobSaleReturnDetailOrderInfo.class)).collect(Collectors.toList());
//        List<TobSaleDetailOrderInfo> tobList = tobSaleOrderFacade.queryDetailListByOrderNo(tobSaleReturnOrderInfo.getTobSaleOrderNo());
//        List<TobSaleReturnDetailOrderInfo> tobReturnList = tobSaleReturnOrderFacade.queryDetailListByTobSaleOrderNo(tobSaleReturnOrderInfo.getTobSaleOrderNo());
//        List<String> detailOrderNo = CollUtil.getFieldValues(tobList, "detailOrderNo", String.class);
//        List<String> returnDetailNo = CollUtil.getFieldValues(tobReturnList, "detailOrderNo", String.class);
        TobSaleOrderInfo tobSaleOrderInfo = tobSaleOrderFacade.getTobSaleOrderInfoByOrderNo(tobSaleReturnOrderInfo.getTobSaleOrderNo());
        saleReturnManager.t41(tobSaleReturnOrderInfo, item, tobSaleOrderInfo);
        //创建代办事项
        try {
            SystemTodoAddRequest addRequest = new SystemTodoAddRequest();
            addRequest.setRoleName(commonProperties.getLogisticsRoleName());
            addRequest.setTodoType(SystemTodoTodoTypeEnum.T5.getIntValue());
            addRequest.setDataId(tobSaleReturnOrderInfo.getOrderNo());
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("orderNo", tobSaleReturnOrderInfo.getOrderNo());
            addRequest.setTodoMessage(jsonObject.toJSONString());
            systemTodoFacade.addSystemTodo(addRequest);
        } catch (Exception e) {
            log.error("生成待办失败", e);
        }
        return succeed();
    }


    @Operation(summary = "审批拒绝(订单状态 = 2)")
    @PutMapping("/tobSaleReturnOrder/refuse/{id}")
    public CommonResponse tobSaleReturnRefuse(@PathVariable Long id) {
        tobSaleReturnOrderFacade.refuse(id);
        return succeed();
    }

    @Operation(summary = "提货地点补充")
    @PutMapping("/tobSaleReturnOrder/takePlaceInsert")
    public CommonResponse tobSaleReturnOrderTakePlaceInsert(@RequestBody TobSaleReturnOrderTakePlaceInsertQueryRequest request) {
        tobSaleReturnOrderFacade.tobSaleReturnOrderTakePlaceInsert(request);
        return succeed();
    }

    @Operation(summary = "撤回")
    @PutMapping("/tobSaleReturnOrder/revokeOrder/{id}")
    public CommonResponse tobSaleReturnOrderRevokeOrder(@PathVariable("id") Long id) {
        TobSaleReturnOrderInfo originalTobSaleReturnOrderInfo = tobSaleReturnOrderFacade.selectById(id);
        if (ObjectUtil.isEmpty(originalTobSaleReturnOrderInfo) || (!originalTobSaleReturnOrderInfo.getReturnStatus().equals(TobSaleReturnOrderReturnStatusEnum.S2.getIntValue()) && !originalTobSaleReturnOrderInfo.getReturnStatus().equals(TobSaleReturnOrderReturnStatusEnum.S3.getIntValue()))) {
            throw new RuntimeException("当前状态不能撤回");
        }
        // 如果修改前是3状态，在修改完状态前，需要在platform层调用warehouse的一个facade方法，
        // LogisticsTraceApplyOrderFacade.deleteLogisticsTraceApply删除对应的入库申请
        if (ObjectUtil.isNotEmpty(originalTobSaleReturnOrderInfo) && originalTobSaleReturnOrderInfo.getReturnStatus().equals(TobSaleReturnOrderReturnStatusEnum.S3.getIntValue())) {
            LogisticsTraceApplyDeleteRequest deleteRequest = new LogisticsTraceApplyDeleteRequest();
            deleteRequest.setSourceOrderNo(originalTobSaleReturnOrderInfo.getOrderNo());
            // 详情单号
            List<String> detailOrderNos = tobSaleReturnOrderFacade.queryTobSaleReturnOrderDetailOrderNosByOrderNos(Lists.newArrayList(originalTobSaleReturnOrderInfo.getOrderNo()));
            deleteRequest.setSourceDetailOrderNoList(detailOrderNos);
            deleteRequest.setSourceOrderType(SubjectEnum.T41.getCode());
            logisticsTraceApplyOrderFacade.deleteLogisticsTraceApply(deleteRequest);
        }
        // 修改预售退单状态为1
        tobSaleReturnOrderFacade.tobSaleReturnOrderRevokeOrder(id);
        return succeed();
    }

}